/*
 *
 * Licensed to the Apache Software Foundation (ASF) under one
 * or more contributor license agreements.  See the NOTICE file
 * distributed with this work for additional information
 * regarding copyright ownership.  The ASF licenses this file
 * to you under the Apache License, Version 2.0 (the
 * "License"); you may not use this file except in compliance
 * with the License.  You may obtain a copy of the License at
 *
 *   http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing,
 * software distributed under the License is distributed on an
 * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
 * KIND, either express or implied.  See the License for the
 * specific language governing permissions and limitations
 * under the License.
 *
 */

package org.apache.airavata.metcat.parser;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.xml.xpath.XPath;
import javax.xml.xpath.XPathConstants;
import javax.xml.xpath.XPathExpression;
import javax.xml.xpath.XPathFactory;

import org.w3c.dom.Document;
import org.w3c.dom.Node;

public class DOMNodeParser implements XMLNodeCapturable {
	
	@Override
	public Map<String, String> parseXMLNodes(Document doc, Map<String, List<IndexAttribute>> metadataIndices) throws Exception {
		XPathFactory factory = XPathFactory.newInstance();
		Map<String, String> indices = new HashMap<String, String>();
		
		for (String namespace : metadataIndices.keySet()) {

			List<IndexAttribute> indexlist = metadataIndices.get(namespace);
			
			for (IndexAttribute iattr : indexlist) {
				
				XPath xpath = factory.newXPath();
				//xpath.setNamespaceContext(null);
				XPathExpression xexp = xpath.compile(iattr.getXPath());
			    Node n = (Node) xexp.evaluate(doc, XPathConstants.NODE);
				String val = xpath.evaluate(iattr.getXPath(), doc);
				if (n==null) continue;
				
				indices.put(iattr.getLabel(), val);
			}	
		
		}
		
		doc = null;
		factory = null;
		
		return indices;
	}

}
